package com.lincoln.framework.service;

import com.lincoln.framework.entity.Member;
import com.lincoln.framework.hibernate.SimpleHibernateTemplate;
import com.lincoln.framework.utils.StringUtilsEx;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 会员(用户)service
 * Created by Lincoln on 2017/10/18.
 */
@Service
@Transactional
public class MemberService extends BaseService<Member> {
    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        dao = new SimpleHibernateTemplate<>(sessionFactory, Member.class);
    }

    /**
     * 查询数据
     *
     * @param criteria
     * @param parameters
     * @return
     */
    public Criteria createCriteria(Criteria criteria, Map<String, Object> parameters) {
        if (!StringUtilsEx.isNullOrEmpty((String) parameters.get("nickName"))) {
            criteria.add(Restrictions.like("nickName", "%" + parameters.get("nickName") + "%"));
        }
        if (!StringUtilsEx.isNullOrEmpty((String) parameters.get("status"))) {
            criteria.add(Restrictions.eq("status",parameters.get("status")));
        }
        return criteria;
    }

    public List<Member> findAllMemberOrderByScore() {
        Criteria criteria = this.dao.createCriteria();
        criteria.addOrder(Order.asc("sort"));
        criteria.addOrder(Order.desc("updateTime"));
//        criteria.addOrder(Order.desc("money"));
        return findList(criteria);
    }

    public List<Member> findAll(){
        Criteria criteria = this.dao.createCriteria();
        criteria.addOrder(Order.asc("sort"));
        criteria.addOrder(Order.desc("updateTime"));
        criteria.add(Restrictions.ne("status",Member.STATUS_BAN));
        return findList(criteria);
    }

    /**
     * 保存
     */
    public void save(Member t) {
        if (t.getCreateTime() == null) {
            t.setCreateTime(new Date());
        }
        t.setUpdateTime(new Date());
        if(t.getSort() == null){
            t.setSort(Member.SORT_NORMAL);
        }
        this.dao.save(t);
    }

}
